package com.example.tabbar.fragment

import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.tabbar.R
import com.example.tabbar.databinding.FragmentUserBinding
import com.example.tabbar.listener.OnFragmentSwitchListener


class UserFragment : Fragment() {
    private var binding: FragmentUserBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentUserBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val loadFragment = UserListFragment.newInstance()
        loadFragment(loadFragment)

        loadFragment.setListener(object : OnFragmentSwitchListener {
            override fun onFragmentSwitch(fragment: Fragment) {
                loadFragment(fragment)
            }
        })

        // 添加返回栈变化监听器
        childFragmentManager.addOnBackStackChangedListener {
            handleBackStackChanged()
        }
    }

    private fun handleBackStackChanged() {
        // 检查当前显示的fragment
        val visibleFragment = childFragmentManager.fragments.find { !it.isHidden }

        // 如果当前显示的是UserListFragment，则显示add按钮
        if (visibleFragment is UserListFragment ) {
            view?.post {
                updateAddButtonVisibilityInParent()
            }
        }
    }

    fun loadFragment(fragment: Fragment) {

        // 使用hide/show代替replace提高性能
        val transaction = childFragmentManager.beginTransaction()

        // 隐藏所有Fragment
        childFragmentManager.fragments.forEach {
            transaction.hide(it)
        }

        // 显示目标Fragment或添加新Fragment
        if (fragment.isAdded) {
            transaction.show(fragment)
        } else {
            transaction.add(R.id.user_container, fragment)
            if (fragment !is UserListFragment) {
                transaction.addToBackStack(null)
            }
        }

        transaction.commit()

        // 延迟更新父fragment中的add按钮状态
        view?.post {
            updateAddButtonVisibilityInParent()
        }
    }
    private fun updateAddButtonVisibilityInParent() {
        // 通知父fragment更新add按钮状态
        val parentFragment = parentFragment
        if (parentFragment is AccountFragment) {
            parentFragment.updateAddButtonVisibility()
        }
    }


    companion object {

        @JvmStatic
        fun newInstance() =
            UserFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}